package com.adtech.farmProducts.activities.activity.procurement;

import android.content.Context;
import android.content.Intent;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.adtech.common.Common;
import com.adtech.common.http.AsyncHttpPostFormData;
import com.adtech.common.http.AsyncHttpResponse;
import com.adtech.common.http.AsyncOkHttpClient;
import com.adtech.common.http.AsyncResponseHandler;
import com.adtech.common.model.RspModel;
import com.adtech.common.utils.AccountManagers;
import com.adtech.common.widgets.dialog.CustomDialog;
import com.adtech.farmProducts.App;
import com.adtech.farmProducts.R;
import com.adtech.farmProducts.activities.activity.UpdateTagActivity;
import com.adtech.farmProducts.base.BaseNfcActivity;
import com.adtech.farmProducts.model.FUserInfo;
import com.adtech.farmProducts.model.NFCResult;
import com.adtech.farmProducts.model.SourceInfo;
import com.adtech.farmProducts.utils.Constants;
import com.adtech.farmProducts.widget.ClearTextIconEditText;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.lang.reflect.Type;
import java.math.BigDecimal;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Time:2020/6/30
 * Created by xiaocz
 * Describe 集中采购
 */
public class Procurement2Activity extends BaseNfcActivity implements CompoundButton.OnCheckedChangeListener {

    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_state)
    TextView tv_state;
    @BindView(R.id.tv_number)
    TextView tv_number;
    @BindView(R.id.layout_base)
    LinearLayout layout_base;
    @BindView(R.id.edit_gs_name)
    TextView edit_gs_name;
    @BindView(R.id.tv_address)
    TextView tv_address;
    @BindView(R.id.tv_time)
    TextView tv_time;

    @BindView(R.id.tv_code)
    TextView tv_code;
    @BindView(R.id.tv_name)
    TextView tv_name;
    @BindView(R.id.tv_unit)
    TextView tv_unit;
    @BindView(R.id.tv_weight)
    TextView tv_weight;
    CheckBox ck_all, ck_unit_price;

    private String batchNo;
    private int checkState;//0-设置总价 1-设置单价
    private SourceInfo sourceInfos;

    public static void show(Context context) {
        Intent intent = new Intent(context, Procurement2Activity.class);
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutSourceId() {
        return R.layout.activity_procurement2;
    }

    private void showView(SourceInfo sourceInfo) {
        sourceInfos = sourceInfo;
        tv_code.setText(sourceInfo.getSourceCode());
        tv_name.setText(sourceInfo.getProductName());
        tv_unit.setText(sourceInfo.getPackUnit());
        tv_address.setText(sourceInfo.getAddress());
        edit_gs_name.setText(sourceInfo.getCompanyName());
        tv_weight.setText(String.format("%s" + sourceInfo.getUnit(), sourceInfo.getWeight()));
        tv_time.setText(sourceInfo.getHandleTime());
        tv_number.setText(String.format("扫码数量：%s%s", sourceInfo.getTotalNum(), sourceInfo.getPackUnit()));
    }

    public static void show(Context context, String code) {
        Intent intent = new Intent(context, UpdateTagActivity.class);
        intent.putExtra("code", code);
        context.startActivity(intent);
    }

    @Override
    protected void initData() {
        tvTitle.setText("集中采购");
        batchNo = AccountManagers.getUserId() + System.currentTimeMillis();//批次号
        onDialogNFC();
        super.initData();
    }

    /**
     * 采购
     */
    private void purchase(String searchValue) {
        loadingDialogShow(false);
        AsyncOkHttpClient okHttpClient = new AsyncOkHttpClient();
        AsyncHttpPostFormData asyncHttpPostFormData = new AsyncHttpPostFormData();
        asyncHttpPostFormData.addFormData("companyId",new Gson().fromJson(AccountManagers.getAccount(), FUserInfo.class).getInfo().getCompanyId());
        asyncHttpPostFormData.addFormData("batchNo", batchNo);
        asyncHttpPostFormData.addFormData("sourceCode", searchValue);
        okHttpClient.posts(Common.Constant.API_IP + "batchPurchase/purchase", asyncHttpPostFormData, new AsyncResponseHandler() {
            @Override
            public void onFailure(IOException e) {
                onDismiss();
                layout_base.setVisibility(View.GONE);
                e.printStackTrace();
            }

            @Override
            public void onSuccess(AsyncHttpResponse response) {
                onDismiss();
                Type type = new TypeToken<RspModel<SourceInfo>>() {
                }.getType();
                RspModel<SourceInfo> rspModel = getAnalysis(response, type, "采购");
                if (rspModel == null) {
                    return;
                }
                switch (rspModel.getCode()) {
                    case 1:
                        if (rspModel.getData() != null) {
                            tv_state.setVisibility(View.VISIBLE);
                            tv_state.setText("扫码成功！");
                            showView(rspModel.getData());
                            layout_base.setVisibility(View.VISIBLE);
                        }
                        break;
                    default:
                        App.getInstance().showMessage(rspModel.getMessage());
                        break;
                }
            }
        });
    }

    @OnClick({R.id.btn_submit})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_submit:
                onDialogSettleAccounts();
                break;
        }
    }

    /**
     * 完成采购
     */
    private void endProcurement(String batchNo, String address, String totalPrice, String unitPrice) {
        loadingDialogShow(false);
        AsyncOkHttpClient okHttpClient = new AsyncOkHttpClient();
        AsyncHttpPostFormData asyncHttpPostFormData = new AsyncHttpPostFormData();
        asyncHttpPostFormData.addFormData("batchNo", batchNo);//必填：批次号
        asyncHttpPostFormData.addFormData("address", address);//必填：溯源码
        asyncHttpPostFormData.addFormData("totalPrice", totalPrice);//必填：总价，如 300.00
        asyncHttpPostFormData.addFormData("unitPrice", unitPrice);//必填：单价，如 40.23
        asyncHttpPostFormData.addFormData("userId", AccountManagers.getUserId());
        okHttpClient.posts(Common.Constant.API_IP + "batchPurchase/finish", asyncHttpPostFormData, new AsyncResponseHandler() {
            @Override
            public void onFailure(IOException e) {
                onDismiss();
                App.getInstance().showMessage("采购失败");
                e.printStackTrace();
            }

            @Override
            public void onSuccess(AsyncHttpResponse response) {
                onDismiss();
                Type type = new TypeToken<RspModel<String>>() {
                }.getType();
                RspModel<String> rspModel = getAnalysis(response, type, "溯源详情");
                if (rspModel == null) {
                    App.getInstance().showMessage("采购失败");
                    return;
                }
                if (rspModel.getCode() == 1) {
                    App.getInstance().showMessage("采购成功");
                    if (customDialog != null) {
                        customDialog.dismiss();
                    }
                    finish();
                } else {
                    App.getInstance().showMessage("采购失败");
                }
            }
        });
    }

    private BigDecimal decimalUnitPrice, decimalAllPrice;
    private String allPrice = null, unitPrice = null;
    private CustomDialog customDialog;

    private void onDialogSettleAccounts() {
        if (sourceInfos == null) {
            App.getInstance().showMessage("请重新采购！");
            return;
        }
        CustomDialog.Builder builder = new CustomDialog.Builder(mContext);
        View layout = LayoutInflater.from(mContext).inflate(R.layout.dialog_procurement, null);
        TextView tvDialogName = layout.findViewById(R.id.tv_name);
        tvDialogName.setText(String.format("产品名称：%s", tv_name.getText().toString()));
        TextView tvDialogNumber = layout.findViewById(R.id.tv_number);
        tvDialogNumber.setText(String.format("采购数量：%s%s", sourceInfos.getTotalNum(), sourceInfos.getPackUnit()));
        TextView tvDialogWeight = layout.findViewById(R.id.tv_weight);
        tvDialogWeight.setText(String.format("采购重量：%s%s", sourceInfos.getTotalWeight(), sourceInfos.getUnit()));
        ck_all = layout.findViewById(R.id.ck_all);
        ck_unit_price = layout.findViewById(R.id.ck_unit_price);
        ck_all.setOnCheckedChangeListener(this);
        ck_unit_price.setOnCheckedChangeListener(this);
        final ClearTextIconEditText edit_all = layout.findViewById(R.id.edit_all);
        final TextView tv_unit_price = layout.findViewById(R.id.tv_unit_price);
        edit_all.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String newText = s.toString().trim();
                if (newText.length() > 0) {
                    decimalUnitPrice = new BigDecimal(newText).divide(sourceInfos.getTotalWeight(), BigDecimal.ROUND_HALF_UP);
                    decimalUnitPrice = decimalUnitPrice.setScale(2, BigDecimal.ROUND_UP);
                    tv_unit_price.setText(String.format("单价：%s元/%s", decimalUnitPrice.toString(), sourceInfos.getUnit()));
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
        final ClearTextIconEditText edit_unit_price = layout.findViewById(R.id.edit_unit_price);
        final TextView tv_all_price = layout.findViewById(R.id.tv_all_price);
        edit_unit_price.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String newText = s.toString().trim();
                if (newText.length() > 0) {
                    decimalAllPrice = new BigDecimal(newText).multiply(sourceInfos.getTotalWeight());
                    decimalAllPrice = decimalAllPrice.setScale(0, BigDecimal.ROUND_UP);
                    tv_all_price.setText(String.format("总价：%s元", decimalAllPrice.toString()));
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
        builder.setContentView(layout);
        builder.setGravity(Gravity.BOTTOM);
        builder.setDialogWidthAndPX(WindowManager.LayoutParams.MATCH_PARENT);
        builder.setDialogHeightAndPX(WindowManager.LayoutParams.WRAP_CONTENT);
        customDialog = builder.create();
        customDialog.show();
        layout.findViewById(R.id.btn_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                customDialog.dismiss();
            }
        });
        layout.findViewById(R.id.btn_submit).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String all_price = String.valueOf(edit_all.getText()).trim();
                String unit_price = String.valueOf(edit_unit_price.getText()).trim();
                if (checkState == 0) {
                    if ("".equals(all_price)) {
                        App.getInstance().showMessage("请设置总价！");
                    }
                    allPrice = all_price;
                    unitPrice = decimalUnitPrice.toString();
                } else {
                    if ("".equals(unit_price)) {
                        App.getInstance().showMessage("请设置单价！");
                    }
                    allPrice = decimalAllPrice.toString();
                    unitPrice = unit_price;
                }
                if (Constants.getLocation() != null) {
                    String address = Constants.getLocation().getAddress();
                    if (address != null) {
                        int index = address.indexOf("靠近");
                        endProcurement(batchNo, index > 0 ? address.substring(0, index) : address, allPrice, unitPrice);
                    }
                } else {
                    App.getInstance().showMessage("定位失败！");
                }
                customDialog.dismiss();
            }
        });
    }

    @Override
    protected void onNewIntent(Intent intent) {
        Tag detectedTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
        NFCResult result = resolveVerifyIntent(detectedTag);
        if (result != null) {
            if(result.isState()){
                tv_code.setText(result.getResult().getUid());
                purchase(result.getResult().getUid());
                if(dialog!=null){
                    dialog.dismiss();
                }
            }else {
                App.getInstance().showMessage(result.getMessage());
            }
        }
    }

    @Override
    public void onCheckedChanged(CompoundButton view, boolean isCheck) {
        if (view.isPressed()) {
            switch (view.getId()) {
                case R.id.ck_all:
                    if (isCheck) {
                        ck_unit_price.setChecked(false);
                        checkState = 0;
                    }
                    break;
                case R.id.ck_unit_price:
                    if (isCheck) {
                        ck_all.setChecked(false);
                        checkState = 1;
                    }
                    break;
            }
        }
    }
}
